package com.borrow.jiemihua.mainUI.fragment;


import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.borrow.jiemihua.R;
import com.borrow.jiemihua.adapter.SuperloanAdapter;
import com.borrow.jiemihua.base.BaseConstant;
import com.borrow.jiemihua.base.BaseFragment;
import com.borrow.jiemihua.base.BaseRVAdapter;
import com.borrow.jiemihua.base.BaseViewHolder;
import com.borrow.jiemihua.base.URLConstant;
import com.borrow.jiemihua.bean.BorrowGBBean;
import com.borrow.jiemihua.bean.MainBannerBean;
import com.borrow.jiemihua.bean.MainHotBean;
import com.borrow.jiemihua.mainUI.activity.ApplyWebViewActivity;
import com.borrow.jiemihua.mainUI.activity.IntelligenHotActivity;
import com.borrow.jiemihua.mainUI.activity.IntelligentMatchActivity;
import com.borrow.jiemihua.mainUI.activity.LoginRegister.LoginActivity;
import com.borrow.jiemihua.mainUI.activity.PlatformDetailsActivity;
import com.borrow.jiemihua.utils.GlideImageLoader;
import com.borrow.jiemihua.utils.SharedPreferencesUtils;
import com.borrow.jiemihua.utils.xutils3.MyCallBack;
import com.borrow.jiemihua.utils.xutils3.XUtil;
import com.borrow.jiemihua.view.MarqueeView;
import com.borrow.jiemihua.view.NoScrollListView;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.duduhuo.custoast.CusToast;

/**
 * A simple {@link Fragment} subclass.
 */
public class BorrowFragment extends BaseFragment implements View.OnClickListener {
    private View view;
    private Banner bannerb;
    private RecyclerView recycler_main;
    private MarqueeView mv_textview;
    private NoScrollListView no_listView;
    private TextView tv_phone;
    private TextView tv_login;
    private LinearLayout ll_login;
    private List<MainHotBean.DataBean> dataBeanList = new ArrayList<>();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public View initView(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.fragment_borrow, null);
        initData();
        initViews();
        upBanberData();
        return view;
    }

    @Override
    public void initData() {
    }

    private void initViews() {
        bannerb = (Banner) view.findViewById(R.id.bannerb);
        mv_textview = (MarqueeView) view.findViewById(R.id.mv_textview);
        no_listView = (NoScrollListView) view.findViewById(R.id.no_listView);
        recycler_main = (RecyclerView) view.findViewById(R.id.recycler_main);
        tv_phone = view.findViewById(R.id.tv_phone);
        tv_login = view.findViewById(R.id.tv_login);
        ll_login = view.findViewById(R.id.ll_login);
        recycler_main.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        view.findViewById(R.id.rl_Intelligengt).setOnClickListener(this);
        view.findViewById(R.id.ll_jsd).setOnClickListener(this);
        view.findViewById(R.id.ll_gxd).setOnClickListener(this);
        view.findViewById(R.id.ll_dejd).setOnClickListener(this);
        view.findViewById(R.id.ll_xkz).setOnClickListener(this);
        view.findViewById(R.id.ll_login).setOnClickListener(this);
    }

    private void getLoanRecordList(List<BorrowGBBean.DataBean> dataBeanList) {
        if (dataBeanList != null && dataBeanList.size() > 0) {
            List<String> dataInfo = new ArrayList<>();
            for (int i = 0; i < dataBeanList.size(); i++) {
                dataInfo.add(dataBeanList.get(i).getTime() + "\n用户" + dataBeanList.get(i).getCellphone() + "在" + dataBeanList.get(i).getTerraceName() + "成功借款" + dataBeanList.get(i).getAmount() + "元");
            }
            mv_textview.startWithList(dataInfo);
        } else {
            List<String> NoDatainfo = new ArrayList<>();
            NoDatainfo.add("用户183*****039在易找钱成功借款1500元");
            NoDatainfo.add("用户152*****063在易找钱成功借款1000元");
            NoDatainfo.add("用户176*****082在易找钱成功借款2000元");
            NoDatainfo.add("用户186*****034在易找钱成功借款3000元");
            NoDatainfo.add("用户177*****056在易找钱成功借款1500元");
            NoDatainfo.add("用户159*****093在易找钱成功借款1000元");
            mv_textview.startWithList(NoDatainfo);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            //登录
            case R.id.ll_login:
                String userid0 = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
                if (TextUtils.isEmpty(userid0)) {
                    jumpActivity(LoginActivity.class, null);
                }
                break;
            //热门
            case R.id.rl_Intelligengt:
                String userid = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
                if (!userid.equals("") && userid != null) {
                    startActivity(new Intent(getActivity(), IntelligenHotActivity.class));
                } else {
                    jumpActivity(LoginActivity.class, null);
                }
                break;
            case R.id.ll_jsd:
                String userid1 = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
                if (!userid1.equals("") && userid1 != null) {
                    startActivity(new Intent(getActivity(), IntelligentMatchActivity.class)
                            .putExtra("typeId", "1"));
                } else {
                    jumpActivity(LoginActivity.class, null);
                }

                break;
            case R.id.ll_gxd:
                String userid2 = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
                if (!userid2.equals("") && userid2 != null) {
                    startActivity(new Intent(getActivity(), IntelligentMatchActivity.class)
                            .putExtra("typeId", "2"));
                } else {
                    jumpActivity(LoginActivity.class, null);
                }

                break;
            case R.id.ll_dejd:
                String userid3 = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
                if (!userid3.equals("") && userid3 != null) {
                    startActivity(new Intent(getActivity(), IntelligentMatchActivity.class)
                            .putExtra("typeId", "3"));
                } else {
                    jumpActivity(LoginActivity.class, null);
                }

                break;
            case R.id.ll_xkz:
                String userid4 = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
                if (!userid4.equals("") && userid4 != null) {
                    startActivity(new Intent(getActivity(), IntelligentMatchActivity.class)
                            .putExtra("typeId", "4"));
                } else {
                    jumpActivity(LoginActivity.class, null);
                }

                break;
            default:
                break;
        }
    }

    private void initBanner(final List<MainBannerBean.DataBean> dataBeanList) {
        List<String> img = new ArrayList<>();
        for (int i = 0; i < dataBeanList.size(); i++) {
            img.add(dataBeanList.get(i).getPicUrl());
        }
        bannerb.setImageLoader(new GlideImageLoader());
        bannerb.setImages(img);
        bannerb.setDelayTime(10000);
        bannerb.start();
        bannerb.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                String userid = SharedPreferencesUtils.getString(getContext(), BaseConstant.SPConstant.USERID, "");
                if (!TextUtils.isEmpty(userid)) {
                    startActivity(new Intent(getActivity(), ApplyWebViewActivity.class)
                            .putExtra("name", "")
                            .putExtra("url", dataBeanList.get(position).getLinkUrl()));
                } else {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                    CusToast.showToast("请先登录");
                }
            }
        });
    }

    private SuperloanAdapter superloanAdapter;

    private void initRecycle() {
        superloanAdapter = new SuperloanAdapter(getActivity());
        no_listView.setAdapter(superloanAdapter);
        no_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startActivity(new Intent(getActivity(), PlatformDetailsActivity.class)
                        .putExtra("terraceId", dataBeanList.get(position).getTerraceId() + ""));
            }
        });
        superloanAdapter.setData(dataBeanList);
        recycler_main.setAdapter(new BaseRVAdapter(getActivity(), dataBeanList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.main_recycler_item2;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
//                ImageView iv_main_image = holder.getImageView(R.id.iv_main_image);
//                Glide.with(getActivity()).load(dataBeanList.get(position).getLogo()).into(iv_main_image);
//                String maxM = String.valueOf(dataBeanList.get(position).getMaxAmount());
//                String minM = String.valueOf(dataBeanList.get(position).getMinAmount());
//                String manED = "";
//                String minED = "";
//                DecimalFormat df = new DecimalFormat("######0.0");
//                if (!maxM.equals("")) {
//                    if (maxM.length() >= 5) {
//                        String str = String.valueOf(df.format(Double.parseDouble(maxM) / 10000));
//                        int ii = Integer.parseInt(str.substring(str.length() - 1, str.length()));
//                        if (ii > 0) {
//                            manED = str + "万";
//                        } else {
//                            manED = String.valueOf(Integer.parseInt(maxM) / 10000) + "万";
//                        }
//                    } else if (maxM.length() == 4) {
//                        String str = String.valueOf(df.format(Double.parseDouble(maxM) / 1000));
//                        int ii = Integer.parseInt(str.substring(str.length() - 1, str.length()));
//                        if (ii > 0) {
//                            manED = str + "千";
//                        } else {
//                            manED = String.valueOf(Integer.parseInt(maxM) / 1000) + "千";
//                        }
//                    } else if (maxM.length() < 4) {
//                        manED = maxM;
//                    }
//                }
//                if (!minM.equals("")) {
//                    if (minM.length() >= 5) {
//                        String str = String.valueOf(df.format(Double.parseDouble(minM) / 10000));
//                        int ii = Integer.parseInt(str.substring(str.length() - 1, str.length()));
//                        if (ii > 0) {
//                            minED = str + "万";
//                        } else {
//                            minED = String.valueOf(Integer.parseInt(minM) / 10000) + "万";
//                        }
////                        minED=String.valueOf(df.format(Double.parseDouble(minM)/10000))+"万";
//                    } else if (minM.length() == 4) {
//                        String str = String.valueOf(df.format(Double.parseDouble(minM) / 1000));
//                        int ii = Integer.parseInt(str.substring(str.length() - 1, str.length()));
//                        if (ii > 0) {
//                            minED = str + "千";
//                        } else {
//                            minED = String.valueOf(Integer.parseInt(minM) / 1000) + "千";
//                        }
////                        minED=String.valueOf(df.format(Double.parseDouble(minM)/1000))+"千";
//                    } else if (minM.length() < 4) {
//                        minED = minM;
//                    }
//                }
//
//                holder.getTextView(R.id.tv_kded).setText(minM + "元" + "~" + maxM + "元");
//                holder.getTextView(R.id.tv_name).setText(dataBeanList.get(position).getName());
//                String str = "最低利率：<font color= '#ff4e4e'>" + dataBeanList.get(position).getRateStr().substring(0, dataBeanList.get(position).getRateStr().length() - 1) + "</font> " + "/月";
////                tvAboutMe1.setText(Html.fromHtml("交易明细：<font color= '#46c98d'>" + "姓名：" + "<big>" + name + "</big></font> " + "日期：17-01-06  20:00"));
//                holder.getTextView(R.id.tv_lv).setText(Html.fromHtml(str));
////                holder.getTextView(R.id.tv_lv).setText("最低利率 " + dataBeanList.get(position).getRateStr());
//                holder.getTextView(R.id.tv_peonum).setText(String.valueOf(dataBeanList.get(position).getApplyForCount()));
//                if (dataBeanList.get(position).getLendType() == 1) {
//                    holder.getTextView(R.id.tv_dklx).setText("现金贷");
//                } else if (dataBeanList.get(position).getLendType() == 2) {
//                    holder.getTextView(R.id.tv_dklx).setText("信用贷");
//                } else if (dataBeanList.get(position).getLendType() == 3) {
//                    holder.getTextView(R.id.tv_dklx).setText("大额贷");
//                }
//                double time = dataBeanList.get(position).getQuickestTime() / 60;
//                holder.getTextView(R.id.tv_fktime).setText(dataBeanList.get(position).getQuickestTimeStr() + "放款");
//                holder.getView(R.id.ll_item_all).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//
//                        Bundle bundle = new Bundle();
//                        bundle.putSerializable("dataBeam", dataBeanList.get(position));
//                        bundle.putString("terraceId", String.valueOf(dataBeanList.get(position).getTerraceId()));
//                        Intent intent = new Intent(getActivity(), PlatformDetailsActivity.class);
//                        intent.putExtras(intent);
//                        startActivity(intent);
//                    }
//                });
            }

        });
    }

    @Override
    public void onResume() {
        super.onResume();
        upBanberData();
        upHotPTData();
        upMessageData();
        String phone = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.MOBILEPHONE, "");
        if (!TextUtils.isEmpty(phone) && phone.length() > 9) {
            StringBuilder builder = new StringBuilder(phone);
            builder.replace(3, 7, "****");
            tv_phone.setText(builder.toString());
            tv_login.setText("欢迎您");
            tv_phone.setVisibility(View.VISIBLE);
        } else {
            tv_login.setText("登录");
            tv_phone.setText("");
            tv_phone.setVisibility(View.GONE);
        }
    }

    //首页banner
    private void upBanberData() {
        XUtil.Get(URLConstant.BANNER, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
//                Log.i("==首页Banner",result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    if (res.equals("1")) {
                        Gson gson = new Gson();
                        MainBannerBean bannerBean = gson.fromJson(result, MainBannerBean.class);
                        List<MainBannerBean.DataBean> dataBeanList = bannerBean.getData();
                        initBanner(dataBeanList);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
            }
        });
    }

    private void upMessageData() {
        Map<String, String> map = new HashMap<>();
        map.put("page", "1");
        map.put("pageSize", "12");
        XUtil.Get(URLConstant.GEE_MESSAGE, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
//                Log.i("==首页广播",result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    if (res.equals("1")) {
                        Gson gson = new Gson();
                        BorrowGBBean borrowGBBean = gson.fromJson(result, BorrowGBBean.class);
                        List<BorrowGBBean.DataBean> dataBeanList = borrowGBBean.getData();
                        getLoanRecordList(dataBeanList);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
            }
        });
    }

    private void upHotPTData() {
        Map<String, String> map = new HashMap<>();
        map.put("isHot", "2");
        map.put("page", "1");
        map.put("pageSize", "12");
        map.put("showChannel", "1");

//        Set keys = map.keySet();
//        if (keys != null) {
//            Iterator iterator = keys.iterator();
//            while (iterator.hasNext()) {
//                Object key = iterator.next();
//                Object value = map.get(key);
//                Log.e("--热门列表参数--" + key, "----"+URLConstant.SHOUYEREMEN + value + "\n");
//            }
//        }
        showDialog();
        XUtil.Get(URLConstant.SHOUYEREMEN, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
//                Log.i("==热门列表",result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    if (res.equals("1")) {
                        Gson gson = new Gson();
                        MainHotBean mainHotBean = gson.fromJson(result, MainHotBean.class);
                        dataBeanList = mainHotBean.getData();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                initRecycle();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
                closeDialog();
            }
        });
    }
}
